import { useState } from "react";
import { useTasksDispatch } from "./TasksContext";
import { ADD_TODO } from "./action";

let nextId = 3;
function AddTodo() {
  const dispatch = useTasksDispatch();
  const [title, setTitle] = useState("");

  const onAddTodo = (title: string) => {
    if (title.trim() === "") {
      return;
    }
    dispatch !== null &&
      dispatch({
        type: ADD_TODO,
        payload: {
          id: nextId++,
          title
        }
      });
  };

  return (
    <>
      <input
        placeholder="Add todo"
        value={title}
        onKeyUp={e => {
          if (e.key === "Enter") {
            setTitle("");
            onAddTodo(title);
          }
        }}
        onChange={e => setTitle(e.target.value)}
      />
      &nbsp;
      <button
        onClick={() => {
          setTitle("");
          onAddTodo(title);
        }}
      >
        添加
      </button>
    </>
  );
}

export default AddTodo;
